# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

import json
import re
from scrapy import Request
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline


class ChanelPipeline(object):
    def __init__(self, location):
        self.file = open(location, 'a', encoding='utf-8')

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            location=crawler.settings.get('DATA_LOCATION'),
        )

    def open_spider(self, spider):
        pass

    def close_spider(self, spider):
        self.file.close()

    def process_item(self, item, spider):
        line = json.dumps(dict(item), ensure_ascii=False) + "\n"
        self.file.write(line)
        print('数据保存至本地成功')
        return item


class MyImagesPipeline(ImagesPipeline):

    def get_media_requests(self, item, info):
        yield Request(url=item['pic'])

    def file_path(self, request, response=None, info=None):
        url = request.url
        file_name = re.findall('.*skus.*/.*?\.(.*)', url)[0]
        return file_name

    def item_completed(self, results, item, info):
        image_paths = [x['path'] for ok, x in results if ok]
        if not image_paths:
            raise DropItem("Item contains no images")
        print('图片下载成功：', image_paths[0])
        return item
